﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net;
using System.IO;
using Newtonsoft.Json;
using DataObjects;
using Resources;
using GT5RemoteMobile.Services;

namespace GT5RemoteMobile
{
    public partial class landing : System.Web.UI.Page
    {
        protected string sessionId;
        protected string psnId;
        protected Profile psnProfile;
        protected string jsessionId;

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack && Request.QueryString["insession"] == null)
            {
                if (Session["jsessionid"] == null)
                    Response.Redirect("default.aspx");
                sessionId = Request.QueryString["sessionId"];

                bool success = false;
                int retryCount = 5;

                while (!success)
                {
                    try
                    {
                        if (retryCount == 0)
                            break;
                        GetPSNID();
                        success = true;
                    }
                    catch (Exception)
                    {
                        success = false;
                        retryCount--;
                    }
                }

                if (!success)
                    Response.Redirect("default.aspx");

                Session.Add("psnid", psnId);
                jsessionId = Session["jsessionid"].ToString();

                success = false;
                retryCount = 5;

                while (!success)
                {
                    try
                    {
                        if (retryCount == 0)
                            break;
                        psnProfile = HelperRequests.GetProfile(psnId, jsessionId);
                        success = true;
                    }
                    catch (Exception)
                    {
                        success = false;
                        retryCount--;
                    }
                }

                if(!success)
                    Response.Redirect("default.aspx");

                Session.Add("psnUser", psnProfile);

                jsessionId = Session["jsessionid"].ToString();

                success = false;
                retryCount = 5;

                while (!success)
                {
                    try
                    {
                        if (retryCount == 0)
                            break;
                        GetFriendsList();
                        success = true;
                    }
                    catch (Exception)
                    {
                        success = false;
                        retryCount--;
                    }
                }

                if (!success)
                    Response.Redirect("default.aspx");
            }
            else
            {
                psnId = Session["psnid"].ToString();
                psnProfile = (Profile)Session["psnUser"];
                jsessionId = Session["jsessionid"].ToString();
                userId.InnerText = "PSN ID: " + psnId;
            }
        }

        private void GetFriendsList()
        {
            HttpWebRequest friendsList = WebRequest.Create(new Uri("https://us.gran-turismo.com/us/gt5/user/" + psnId + "/")) as HttpWebRequest;
            // hack to ignore invalid certs (used for dev proxy)
            //ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
#if(DEBUG)
            //friendsList.Proxy = new WebProxy("localhost", 8888);
#endif
            friendsList.Method = "GET";
            friendsList.Accept = "text/javascript, text/html, application/xml, text/xml, */*";
            friendsList.Referer = "https://us.gran-turismo.com/us/gt5/signin/";
            friendsList.Headers.Add("Cookie", jsessionId);
            List<string> friendIds = new List<string>();
            using (HttpWebResponse response = friendsList.GetResponse() as HttpWebResponse)
            {
                StreamReader reader = new StreamReader(response.GetResponseStream());
                bool read = true;
                string line = "";
                List<Profile> listFriends = new List<Profile>();
                do
                {
                    line = reader.ReadLine();
                    if (line.Contains("friend_id_list["))
                    {
                        string fid = line.Split('=')[1].Replace('"', ' ').Trim().TrimEnd(';');
                        friendIds.Add(fid);

                        // can't get friend's profile from here for some reason?
                        Profile p = new Profile();
                        p.ID = fid;
                    }
                    else
                    {
                        if (friendIds.Count > 0)
                        {
                            break;
                        }
                    }
                } while (read);
                Session.Add("friends", friendIds.ToArray<string>());
            }
        }

        private void GetPSNID()
        {
            HttpWebRequest request = WebRequest.Create(new Uri("http://api.geekweb.org/psn/getid/out.php?" + Session["localjsessionid"])) as HttpWebRequest;
            using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
            {
                StreamReader reader = new StreamReader(response.GetResponseStream());
                psnId = reader.ReadToEnd();
                userId.InnerText = "PSN ID: " + psnId;
            }
        }

        public void StartNewRace(object sender, EventArgs e)
        {
            GetDrivers driverUtil = new GetDrivers();
            driverUtil.jsessionId = Session["jsessionid"].ToString();
            List<RemoteRaceDriver> drivers = driverUtil.LookupDrivers(Session["psnid"].ToString());
            foreach (RemoteRaceDriver driver in drivers)
            {
                if (driver.Status == 0)
                    Response.Redirect("landing.aspx?insession=true&error=nops3");
                if (driver.Status == 1)
                    Response.Redirect("newRace.aspx");
                if(driver.Status == 2 || driver.Status == 3)
                    Response.Redirect("RaceStatus.aspx");
                Console.WriteLine("Race Status: " + driver.Status);
            }
            Response.Redirect("newRace.aspx");
        }
    }
}